package be.vdab.Servlets;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.vdab.dao.SauzenDAO;
import be.vdab.entities.Saus;
import be.vdab.entities.Spel;

@WebServlet("/sauzen/raden.htm")
@MultipartConfig
public class SauzenRadenServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String VIEW = "/WEB-INF/JSP/raden.jsp";
	private static final String REDIRECT_URL = "/sauzen/raden.htm";
	private static final String SPEL = "spel";
	private final SauzenDAO sausDAO = new SauzenDAO();
	private Saus randomSaus;

	protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if (session.getAttribute(SPEL) == null){
			Collection<Saus> sauzen = sausDAO.findAll();
		    int randomIndex = new Random().nextInt(sauzen.size());
		    Iterator<Saus> i = sauzen.iterator();
	    	for (int teller = 0; teller < randomIndex; teller++){
	    		randomSaus = (Saus) i.next();
	    	}
		    Spel spel = new Spel(randomSaus.getNaam());
		    session.setAttribute(SPEL, spel);

		} 
		
		RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
		dispatcher.forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		if (request.getParameter("nieuwSpel") != null) {
		      session.removeAttribute(SPEL);
		} else {
			String letter = request.getParameter("letter");
		    Spel spel = (Spel) session.getAttribute(SPEL);
		    if (spel != null && letter != null && !letter.isEmpty()) {
		    	spel.doeGok(letter.charAt(0));
		        session.setAttribute(SPEL, spel);
		    }
		}
		response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + REDIRECT_URL));
	}
}
